
import TempColor from "./TempColor";

const { ccclass, property, requireComponent } = cc._decorator;

@ccclass
@requireComponent(cc.Sprite)
export default class DrawV1 extends cc.Component {


    @property(cc.Graphics)
    g: cc.Graphics = null;

    @property
    radius: number = 30;
    //当前使用的颜色
    protected color: cc.Color;
    //绘制八寸
    protected stepBuffer: TempColor[] = []
    //当前数据存储
    protected tempBuffer: TempColor = new TempColor();

    start() {
        this.color = this.node.color;
        this.node.on(cc.Node.EventType.TOUCH_START, this.touchStart, this)
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this)
        this.node.on(cc.Node.EventType.TOUCH_END, this.touchCancel, this)
    }

    onEnable() {

    }




    touchCancel() {

        this.clearContent();

    }


    clearContent() {
        this.tempBuffer.color = this.color;
        this.stepBuffer.push(this.tempBuffer)
        //回退次数限制
        if (this.stepBuffer.length > 20) {
            this.stepBuffer.shift();
        }
        this.tempBuffer = new TempColor()
    }

    touchStart(e) {
        this.painting(this.node.convertToNodeSpaceAR(e.getLocation()))
    }

    touchMove(e: cc.Touch) {
        this.painting(this.node.convertToNodeSpaceAR(e.getLocation()))
    }

    painting(pos) {
        this.tempBuffer.push(pos)
        this.drawing(pos)
    }

    //回退
    back() {
        if (this.stepBuffer.length > 0) {
            this.stepBuffer.pop();
        }
        this.g.clear()
        for (let index = 0; index < this.stepBuffer.length; index++) {
            const temp = this.stepBuffer[index];
            let data = temp.list;
            this.setColor(temp.color)
            // cc.log(" data.length ", data.length)
            for (let j = 0; j < data.length; j++) {
                const element = data[j];
                this.drawing(element)
            }
        }
    }

    clear() {
        this.stepBuffer.length = 0;
        this.tempBuffer = new TempColor()
        this.g.clear()
    }



    drawing(element) {
        let g = this.g;
        let x = element.x;
        let y = element.y;
        g.moveTo(x, y)
        g.circle(x, y, this.radius)
        g.close();
        g.fill();
    }

    setColor(color: cc.Color) {
        this.color = color;
        this.g.fillColor = color;
        this.g.strokeColor = color;
    }


}
